package yja.gzw.app.gedingdanzhuangtai

import AuthResult
import PayResult
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.widget.ImageView
import android.widget.RadioButton
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.Observer
import cn.jzvd.Jzvd
import com.alipay.sdk.app.PayTask
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.tencent.imsdk.v2.V2TIMConversation
import com.tencent.qcloud.tuicore.TUIConstants
import com.tencent.qcloud.tuikit.tuichat.classicui.page.TUIC2CChatActivity
import yja.gzw.app.R
import yja.gzw.app.activity.JvjueActivity
import yja.gzw.app.base.BaseActivity
import yja.gzw.app.databinding.ActivityDaiquerengBinding
import yja.gzw.app.model.UserData
import yja.gzw.app.viewmodel.Mainviewmodel
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter

class DaiquerengActivity :BaseActivity<Mainviewmodel, ActivityDaiquerengBinding>(R.layout.activity_daiquereng){
    private lateinit var bottomSheetDialog: BottomSheetDialog
    val SDK_PAY_FLAG: Int = 1
        var userid=""
    val SDK_AUTH_FLAG: Int = 2
    var qian=""
   var types=""
    var leixing="wechat"
    override fun initView() {
        val ids =intent.getStringExtra("ids")
        val type =intent.getStringExtra("type")
     //   Toast.makeText(this,type, Toast.LENGTH_SHORT).show()

        binding.sixing.setOnClickListener {
            Log.e("userid","userid是"+userid)
            val intent = Intent(this, TUIC2CChatActivity::class.java)
            intent.putExtra(TUIConstants.TUIChat.CHAT_ID,userid)
            intent.putExtra(TUIConstants.TUIChat.CHAT_TYPE, V2TIMConversation.V2TIM_C2C)
            startActivity(intent)


        }




        if(type!="3"){

            viewmodel.onxiangqingwang2(UserData.token, mapOf("order_id" to ids!!))
        }else{
            viewmodel.onxiangqingwang(UserData.token, mapOf("order_id" to ids!!))

        }






        binding.jujue.setOnClickListener {
            finish()
            val inten=Intent(this, JvjueActivity::class.java)
            inten.putExtra("oids",ids)
            startActivity(inten)

        }
        binding.queding.setOnClickListener {

            if(type!="3"){
            //todo 确认订单
            viewmodel.onsanquerengwang(UserData.token, mapOf("order_id" to ids))


            }else{
                bottomSheetDialog = BottomSheetDialog(this)
                val view = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_layout, null)
                bottomSheetDialog.setContentView(view)
                val title=view.findViewById<TextView>(R.id.title)
                val chacha=view.findViewById<ImageView>(R.id.chacha)
                val okButton=view.findViewById<TextView>(R.id.okButton)
                val xuan1=view.findViewById<RadioButton>(R.id.xuan1)
                val xuan2=view.findViewById<RadioButton>(R.id.xuan2)
                title.text="￥${qian}"


                chacha.setOnClickListener {
                    bottomSheetDialog.dismiss()
                }

                okButton.setOnClickListener {

                    if(types=="1"){
                        types="three"
                    }else if(types=="2"){
                        types="four"
                    }else{
                        types="fine"
                    }

                    if(xuan1.isChecked){
                        leixing="wechat"

                    }else{
                        leixing="alipay"

                    }



                    viewmodel.onZhifushowwang(UserData.token, mapOf("order_id" to ids, "type" to types, "pay_type" to leixing,"method" to "app"))


                }

                bottomSheetDialog.show()



            }






        }


    }

    override fun dataObservese() {

        viewmodel.onsanquereng.observe(this, Observer {

            if(it.code==1){
                finish()
                Toast.makeText(this,it.msg, Toast.LENGTH_SHORT).show()
            }else{
                Toast.makeText(this,it.msg, Toast.LENGTH_SHORT).show()
            }

        })


        viewmodel.onZhifushow.observe(this, Observer {
            if(it.code==1){

                zhifujieu(it.data.toString())

            }else{


            }

        })


        viewmodel.onxiangqing.observe(this, Observer {
            if(it.code==1){



                if(it.data.fine_release_type==1){
                    binding.fabumoshioqian.text="自己定价"
                }else if(it.data.fine_release_type==2){
                    binding.fabumoshioqian.text="第二方定价"
                }else{
                    binding.fabumoshioqian.text="第二方竞价"
                }
                binding.platformId.text=it.data.platform_id
                binding.weizhi.text=it.data.address
                binding.neirong.text=it.data.content
                binding.huobiaoqian.text=it.data.need_title
                binding.wengzisucaishow.text= it.data.label
                binding.biaotifu.text=it.data.title



                binding. videoView.setUp(it.data.video_url.toString(), "播放视频", Jzvd.SCREEN_WINDOW_NORMAL)
                binding. videoView.thumbImageView.setImageURI(Uri.parse("http://p.qpic.cn/videoyun/0/2449_43b6f696980311e59ed467f22794e792_1/640"));
                types=it.data.type

                userid=it.data.price_list[0].user_id.toString()

                binding.biaoti.text=it.data.title

                if(it.data.type=="1"){
                    binding.zhuanquleixing.text="三元视频"

                }else if(it.data.type=="2"){
                    binding.zhuanquleixing.text="四元视频"
                }else{
                    binding.zhuanquleixing.text="精品视频"
                }
                binding.fabumoshioqian.text="已出价￥${it.data.pay_price}"

                binding.wengzisucaishow.text=it.data.text_material
                val requestOptions = RequestOptions.bitmapTransform(CircleCrop())
                Glide.with(this).load("http://117ai.32.hzgqapp.com/"+it.data.price_list[0].avatar)
                    .apply(requestOptions)
                    .into(binding.touxiang)
                binding.name.text=it.data.price_list[0].username
                binding.dingdanbiaohao.text=it.data.order_no
                val timestamp = 1739169752L
                // 将秒级时间戳转换为 Instant 对象
                //todo 爆红不必理会
                val instant = Instant.ofEpochSecond(timestamp)

                val zoneId = ZoneId.systemDefault()
                // 将 Instant 对象转换为 LocalDateTime 对象
                val localDateTime = instant.atZone(zoneId).toLocalDateTime()
                // 定义日期时间格式化模式
                val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                // 格式化日期时间
                val formattedDateTime = localDateTime.format(formatter)
                binding.dindanfabushijian.text=it.data.create_time_text
                binding.dindanchengjiaoshijian.text=it.data.confirm_time_text
                binding.dindanwanchengshijian.text=it.data.delivery_time_text
                binding.dindanjiage.text="￥${it.data.price_list[0].price}"
                qian=it.data.price_list[0].price
                binding.dingjiaqianshu.text="第二方定价：￥${it.data.price_list[0].price}"


            }else{
                Toast.makeText(this,it.msg, Toast.LENGTH_SHORT).show()
            }

        })
        viewmodel.onxiangqing2.observe(this, Observer {
            if(it.code==1){



                if(it.data.fine_release_type==1){
                    binding.fabumoshioqian.text="自己定价"
                }else if(it.data.fine_release_type==2){
                    binding.fabumoshioqian.text="第二方定价"
                }else{
                    binding.fabumoshioqian.text="第二方竞价"
                }
                binding.platformId.text=it.data.platform_id
                binding.weizhi.text=it.data.address
                binding.neirong.text=it.data.content
                binding.huobiaoqian.text=it.data.need_title
                binding.wengzisucaishow.text= it.data.label
                binding.biaotifu.text=it.data.title



                binding. videoView.setUp(it.data.video_url.toString(), "播放视频", Jzvd.SCREEN_WINDOW_NORMAL)
                binding. videoView.thumbImageView.setImageURI(Uri.parse("http://p.qpic.cn/videoyun/0/2449_43b6f696980311e59ed467f22794e792_1/640"));
                types=it.data.type

                userid=it.data.publisher.id.toString()

                binding.biaoti.text=it.data.title

                if(it.data.type=="1"){
                    binding.zhuanquleixing.text="三元视频"

                }else if(it.data.type=="2"){
                    binding.zhuanquleixing.text="四元视频"
                }else{
                    binding.zhuanquleixing.text="精品视频"
                }
                binding.fabumoshioqian.text="已出价￥${it.data.pay_price}"

                binding.wengzisucaishow.text=it.data.text_material
                val requestOptions = RequestOptions.bitmapTransform(CircleCrop())
                Glide.with(this).load("http://117ai.32.hzgqapp.com/"+it.data.publisher.avatar)
                    .apply(requestOptions)
                    .into(binding.touxiang)
                binding.name.text=it.data.publisher.username
                binding.dingdanbiaohao.text=it.data.order_no
                val timestamp = 1739169752L
                // 将秒级时间戳转换为 Instant 对象
                //todo 爆红不必理会
                val instant = Instant.ofEpochSecond(timestamp)

                val zoneId = ZoneId.systemDefault()
                // 将 Instant 对象转换为 LocalDateTime 对象
                val localDateTime = instant.atZone(zoneId).toLocalDateTime()
                // 定义日期时间格式化模式
                val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                // 格式化日期时间
                val formattedDateTime = localDateTime.format(formatter)
                binding.dindanfabushijian.text=it.data.create_time_text
                binding.dindanchengjiaoshijian.text=it.data.confirm_time_text
                binding.dindanwanchengshijian.text=it.data.delivery_time_text
                binding.dindanjiage.text="￥${it.data.pay_price}"
                qian=it.data.pay_price
                binding.dingjiaqianshu.text="第二方定价：￥${it.data.pay_price}"


            }else{
                Toast.makeText(this,it.msg, Toast.LENGTH_SHORT).show()
            }

        })
    }

    fun zhifujieu(info: String) {
        val orderInfo = info // 订单信息
        val payRunnable = Runnable {
            val alipay = PayTask(this)
            val result = alipay.payV2(orderInfo, true)
            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            mHandler.sendMessage(msg)
        }

        val payThread = Thread(payRunnable)
        payThread.start()
    }


    @SuppressLint("HandlerLeak")
    var mHandler: Handler = object : Handler() {
        @Suppress("unused")
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    Log.e("支付步骤","1")
                    val payResult: PayResult = PayResult(msg.obj as Map<String?, String?>)

                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo: String = payResult.getResult() // 同步返回需要验证的信息
                    val resultStatus: String = payResult.getResultStatus()
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Log.e("支付步骤","2")
                        //todo 支付成功
                        Toast.makeText(this@DaiquerengActivity, "支付成功", Toast.LENGTH_SHORT).show()
                        finish()
                        bottomSheetDialog.dismiss()




                    } else {
                        //todo 放弃支付
                        Log.e("支付步骤","3")
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(this@DaiquerengActivity, "支付失败", Toast.LENGTH_SHORT).show()
                    }
                }

                SDK_AUTH_FLAG -> {
                    Log.e("支付步骤","4")
                    val authResult: AuthResult = AuthResult(msg.obj as Map<String?, String?>, true)
                    val resultStatus: String = authResult.getResultStatus()

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(
                            resultStatus,
                            "9000"
                        ) && TextUtils.equals(authResult.getResultCode(), "200")
                    ) {
                        Log.e("支付步骤","5")
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(this@DaiquerengActivity, "支付成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Log.e("支付步骤","6")
                        // 其他状态值则为授权失败
                        Toast.makeText(this@DaiquerengActivity, "支付失败", Toast.LENGTH_SHORT).show()
                    }
                }

                else -> { Log.e("支付步骤","7")}
            }
        }
    }

}